package com.mac.intellect_flow.admin.controller.system;

import com.mac.intellect_flow.framework.model.LoginUser;
import com.mac.intellect_flow.framework.util.FileUploadUtil;
import com.mac.intellect_flow.framework.util.JwtUtil;
import com.mac.intellect_flow.framework.util.SecurityUtils;
import com.mac.intellect_flow.reply.R;
import com.mac.intellect_flow.sys.entity.SysUser;
import com.mac.intellect_flow.sys.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 * 
 * @author ruoyi
 */
@Tag(name = "个人信息管理")
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private FileUploadUtil FileUploadUtils;

    /**
     * 个人信息
     */
    @Operation(summary = "个人信息")
    @GetMapping
    public R profile() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Map<String, Object> data = new HashMap<>();
        data.put("data", loginUser);
        data.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        data.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return R.success(data);
    }

    /**
     * 修改用户
     */
    @Operation(summary = "修改用户")
    @PutMapping
    public R updateProfile(@RequestBody SysUser user, HttpServletRequest request) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = new SysUser();
        currentUser.setId(loginUser.getId());
        currentUser.setNickName(user.getNickName());
        currentUser.setEmail(user.getEmail());
        currentUser.setPhone(user.getPhone());
        currentUser.setSex(user.getSex());
        if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(currentUser)) {
            return R.error("修改用户'" + loginUser.getUsername() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(currentUser))
        {
            return R.error("修改用户'" + loginUser.getUsername() + "'失败，邮箱账号已存在");
        }
        if (userService.updateUserProfile(currentUser) > 0) {
            // 更新缓存用户信息
            JwtUtil.setRedisUserInfo(request,null,loginUser,true);
            return R.success();
        }
        return R.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Operation(summary = "重置密码")
    @PutMapping("/updatePwd")
    public R updatePwd(String oldPassword, String newPassword, HttpServletRequest request) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!passwordEncoder.matches(oldPassword,password)) {
            return R.error("修改密码失败，旧密码错误");
        }
        if (passwordEncoder.matches(newPassword, password)) {
            return R.error("新密码不能与旧密码相同");
        }
        newPassword = passwordEncoder.encode(newPassword);
        if (userService.resetUserPwd(userName, newPassword) > 0) {
            // 更新缓存用户密码
            loginUser.setPassword(newPassword);
            JwtUtil.setRedisUserInfo(request,null,loginUser,true);
            return R.success();
        }
        return R.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Operation(summary = "头像上传")
    @PostMapping("/avatar")
    public R avatar(@RequestParam("avatarfile") MultipartFile file, HttpServletRequest request) throws Exception {
        if (!file.isEmpty()) {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String avatar = FileUploadUtils.upload(file);
            if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
                // 更新缓存用户头像
                loginUser.setAvatar(avatar);
                JwtUtil.setRedisUserInfo(request,null,loginUser,true);
                return R.success(avatar);
            }
        }
        return R.error("上传图片异常，请联系管理员");
    }
}
